import { Message } from 'element-ui'
const OSS = require("ali-oss");

const SUFFIX = /.+(\.\w+)$/,
  TIMEOUT = 60000,
  BYTE = 1024,
  RETRY_COUNT_MAX = 3,
  ACCEPT = {
    zip: 'application/zip,application/x-zip,application/x-zip-compressed',
    pdf: 'application/pdf',
    excel: 'application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    image: 'image/jpeg,image/bmp,image/png,image/gif',
    word: 'application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    ppt: 'application/vnd.ms-powerpoint,application/vnd.openxmlformats-officedocument.presentationml.presentation',
  },
  getAccepts = accept => (Array.isArray(accept) ? accept : [accept]).map(ac => ACCEPT[ac]).join(','),
  beforeCheck = (config, file) => {
    let {max = Number.MAX_VALUE, accept = []} = config || {}, { size, type } = file, accepts = getAccepts(accept).split(',');
    
    //大小限制(M)
    if(Math.pow(BYTE, 2) * max < size){
        Message.warning(`文件不能超过${max}M`);
        return false;
    }
  };

export default {
  functional: true,
  props: {config: Object, limit: Number, percentage: Function},
  render: (h, ctx) => {
    let {props, data: attrs, parent: {$store: { dispatch}}, children} = ctx, { config, limit } = props, retryCount = 0, { accept } = config;
    if(!attrs.attrs.accept && accept){
      attrs.attrs.accept = getAccepts(accept);
    }

    Object.assign(props, {
      action: '',
      beforeUpload: file => beforeCheck(config, file),
      onExceed: () => Message.warning(`最多可以上传${limit}个文件`),
      httpRequest: opts => {
        let { file, onError, onProgress, onSuccess } = opts, { uid, name, type } = file, regExp = /image\/[a-z]{2,4}$/i;
        name = `${uid}${name.replace(SUFFIX, '$1')}`;
        file.isImg = regExp.test(type) ? true : false;

        dispatch('getClient').then(res => {
          let aliClient = new OSS(res), { path } = res, url = path + '/' + name;
          //multipartUpload是阿里云的分片（分段）大文件上传方法，这里也可以用put方法来上传单个小文件(aliClient.put)
          aliClient.multipartUpload(url, file, {
            timeout: TIMEOUT,
            partSize: 500 * BYTE,
            progress: p => {
              onProgress(p * 100, file)
            }
          }).then(r => {
            let { res: { requestUrls } } = r;
            requestUrls = requestUrls.length < 1 ? '' : requestUrls[0]
            if (requestUrls.indexOf('?') > -1) requestUrls = requestUrls.split('?')[0]
            onSuccess({ res: file, url: requestUrls });
          }).catch(err => {
            let { name } = err;
            if (aliClient.isCancel()) {
              console.log('stop-upload!');
            } else {
              Message.error(err);
              onError(err);
              if (name.toLowerCase().indexOf('connectiontimeout') !== -1) {
                if (retryCount < RETRY_COUNT_MAX) {
                  retryCount++;
                  props.httpRequest(opt)
                }
              }
            }
          });;
        })
      }
    })
    return h('el-upload', {props, ...attrs}, children)
  }
}